﻿#region

using System;
using System.ComponentModel;
using System.Threading;
using Radovici.SharedLibrary;
using YouTubePlaylist.Models;

#endregion

namespace YouTubePlaylist.ViewModels
{
    public class PlaylistsViewModel : Notifiable
    {
        private readonly Timer _activeTimer;
        private DateTime _lastActive = DateTime.MinValue;
        private PlaylistsModel _model;

        public PlaylistsViewModel()
        {
            _activeTimer = new Timer(OnActiveTimerCallback, null, int.MaxValue, int.MaxValue);
        }

        public PlaylistsModel PlaylistsModel
        {
            get { return _model; }
            set
            {
                _model = value;
                _model.PropertyChanged += OnModelPropertyChanged;
                Notify("PlaylistsModel");
            }
        }

        public bool IsActive
        {
            get { return DateTime.Now.Subtract(_lastActive) < new TimeSpan(0, 0, 5); }
            set
            {
                _lastActive = value ? DateTime.Now : DateTime.MinValue;
                Notify("IsActive");
                _activeTimer.Change(value ? 0 : int.MaxValue, 5000);
            }
        }

        #region Private methods

        private void OnActiveTimerCallback(object state)
        {
            if (!IsActive)
            {
                _activeTimer.Change(int.MaxValue, int.MaxValue);
            }
            Notify("IsActive");
        }

        private void OnModelPropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            switch (e.PropertyName)
            {
                case "SelectedPlaylist":
                    IsActive = _model.IsPlaylistSelected;
                    break;
            }
        }

        #endregion
    }
}